<?php
class Application_Model_Bet extends App_DbTable
{
	public function __construct($id = null){
		parent::__construct(new Application_Model_DbTable_Bet(), $id);
	}
	
	public function getUser(){
		return $this->_row->findParentRow('Application_Model_DbTable_User', 'User' );
	}
	public function getEvent(){
		return $this->_row->findParentRow('Application_Model_DbTable_Event', 'Event' );
	}
	public function recountBet(){
	    if($this->_row->bet_left > $this->_row->bet_right){
    		$this->_row->bet_result = 'left';
    	}
    	elseif($this->_row->bet_left < $this->_row->bet_right){
    		$this->_row->bet_result = 'right';
    	}
    	else{
    		$this->_row->bet_result = 'draw';
    	}
    	$points = 0;
    	$event = $this->getEvent();
    	if($this->_row->bet_result == $event->result){
    		$points = 1;
    		if($this->_row->bet_left == $event->score_left && $this->_row->bet_right == $event->score_right){
    			$points = 3;
    		}
    	}
    	$this->_row->points = $points;
    	$this->_row->status = 'closed';
    	$this->save();
	}
	public function getAll($pagination = false, $currPage = 1, $checkStatus = true){
		$select = $this->_dbTable->select();
		if($checkStatus){
			$select->where('status = ?', 'opened');
		}
		
		if($pagination){
	       	$paginator = Zend_Paginator::factory($select);
			$paginator->setItemCountPerPage(10);
	        $paginator->setPageRange(3);
	       	$paginator->setCurrentPageNumber($currPage);         
			return $paginator;
		}
		else{
			return $this->_dbTable->fetchAll($select);
		}
	}
	public function get(){
		return $this->_row;
	}
	public function getBet($user_id, $event_id){
		$select = $this->_dbTable->select();
    	if($user_id){
    		$select->where('user_id = ?', (int)$user_id);
    	}
        if($event_id){
    		$select->where('event_id = ?', (int)$event_id);
    	}
    	if($res = $this->_dbTable->fetchRow($select)){
    		$this->_row = $res;
    	}
    	return $res;
	}
}